<template>
  <div class="app-container" style="padding-bottom: 130px;">
    <el-form ref="form" :model="form" :rules="rules" class="form" label-width="150px">
      <el-row :gutter="24" >
        <el-col :span="12">
          <el-form-item label="福卡名称" prop="name" >
            <el-input v-model="form.name" placeholder="请输入福卡名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="状态" :style="{width: '100%'}" clearable size="small">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" >
        <el-col :span="12">
          <el-form-item label="总数量" prop="totalNum">
            <el-input v-model="form.totalNum" placeholder="请输入总数量" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已发放数量" prop="provideNum" label-width="150px">
            <el-input v-model="form.provideNum" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" >
        <el-col :span="12">
          <el-form-item label="机率" prop="rate">
            <el-input v-model="form.rate" placeholder="请输入机率" />
          </el-form-item>
        </el-col>
        <!--<el-col :span="12">
          <el-form-item label="文字介绍" prop="textIntroduction">
            <el-input v-model="form.textIntroduction" type="textarea" placeholder="请输入文字介绍" />
          </el-form-item>
        </el-col>-->
      </el-row>
      <el-row :gutter="24" >
        <el-col :span="12">
          <el-form-item label="正面图片上传" prop="imgPath">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :limit="1"
              :file-list="fileList"
              :headers="headers"
              :before-upload="checkUpload"
              :disabled="flag">
              <img v-if="files.path" :src="base_url+files.path" class="avatar" width="100px" height="100px">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" >
        <el-col :span="12">
          <el-form-item label="反面图片上传" prop="backImgPath">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="uploadSuccess2"
              :limit="1"
              :file-list="fileList2"
              :headers="headers"
              :before-upload="checkUpload"
              :disabled="flag2">
              <img v-if="files.path2" :src="base_url+files.path2" class="avatar" width="100px" height="100px">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
     <!-- <el-form-item label="万寿宫介绍" label-width="150px" prop="wsgIntroduction">
        <Editor v-model="form.wsgIntroduction" style="height: 290px;"/>
      </el-form-item>-->
      <el-form-item size="large">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>

  import { listFk, getFk, delFk, addFk, updateFk, exportFk, delFile} from "@/api/wsg/fk";
  // import Editor from '@/components/Editor';
  import {getToken} from "@/utils/auth";

  export default {
    name: "Fk",
    //components: {
    //  Editor
    //},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 万寿宫-福卡表格数据
        fkList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          wxClientId: undefined,
          name: undefined,
          status: undefined,
          imgPath: undefined,
          totalNum: undefined,
          provideNum: undefined,
          rate: undefined
        },
        fkSize: undefined,
        // 表单参数
        form: {},
        // 状态字典
        statusOptions: [],
        // 表单校验
        rules: {
          name: [
            { required: true, message: "福卡名称不能为空", trigger: "blur" }
          ],
          totalNum: [
            { required: true, message: "总数量不能为空", trigger: "blur" },
            {
              pattern: /^[1-9]\d*$/,
              message: "请输入正确的总数量",
              trigger: "blur"
            }
          ],
          rate: [
            { required: true, message: "几率不能为空", trigger: "blur"},
            {
              pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
              message: "请输入正确的几率",
              trigger: "blur"
            }
          ],
          textIntroduction: [
            { required: true, message: "文字介绍不能为空", trigger: "blur" }
          ],
          wsgIntroduction: [
            { required: true, message: "万寿宫介绍不能为空", trigger: "blur" }
          ],
          status: [
            { required: true, message: "状态不能为空", trigger: "blur" }
          ],
          //imgPath: [
            //{ required: true, message: "图片不能为空", trigger: "blur" }
          //],
        },
        base_url: process.env.VUE_APP_BASE_API,
        //文件列
        fileList: [],
        fileList2: [],
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        //上传地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        //是否禁用上传
        flag: false,
        //是否禁用上传
        flag2: false,
        //图片路径
        files: {path: '', path2: ''},
        // 表单校验
      };
    },
    created() {
      this.mounted();
      this.getDicts("wx_fk_state").then(response => {
        this.statusOptions = response.data;
      });
    },
    watch: {
    $route(){
        this.mounted();
      }
    },
    methods: {
      mounted() {
        this.form.id = this.$route.query.id;
        console.log(this.form.id);
        // 根据id判断是否回显数据
        if(this.form.id != "" && this.form.id != undefined && this.form.id != null){
          getFk(this.$route.query.id).then(response => {
            this.form = response.data;
            this.files.path = response.data.imgPath;
            this.files.path2 = response.data.backImgPath;
          });
        } else {
          this.resetForm();
        }
      },
      // 状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 删除标志字典翻译
      delFlagFormat(row, column) {
        return this.selectDictLabel(this.delFlagOptions, row.delFlag);
      },
      // 内容类型
      contentTypeFormat(row, column) {
        return this.selectDictLabel(this.contentTypeOptions, row.contentType);
      },
      /** 提交按钮 */
      submitForm: function() {
        var imgPath = this.form.imgPath;
        var backImgPath = this.form.backImgPath;
        console.log(imgPath);
        if (imgPath == '' || imgPath == undefined || imgPath == null) {
          this.msgError("请上传正面图片");
          return;
        }
        if (backImgPath == '' || backImgPath == undefined || backImgPath == null) {
          this.msgError("请上传反面图片");
          return;
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateFk(this.form).then(response => {
                console.log(response);
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  var location = '/wsg/fk';
                  this.$router.push({'path':location, name:'Fk', 'query': {}})
                }
              });
            } else {
              addFk(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  var location = '/wsg/fk';
                  this.$router.push({'path':location, name:'Fk', 'query': {}})
                }
              });
            }
          }
        });
      },
      resetForm() {
        this.form = {
          name: undefined,
          status: "0",
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          totalNum: undefined,
          provideNum: undefined,
          rate: undefined
        };
        this.fileList = [];
        this.fileList2 = [];
        this.flag = false
        this.flag2 = false
      },
      picsBeforeUpload(file) {
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        return isRightSize
      },
      handleRemove(file, fileList) {
        console.log("686");
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      /** 上传之前的校验 */
      checkUpload(file) {
        console.log("文件类型", file)
        const imgType = file.type
        //图片不大于2M
        const isLtSize = file.size / 1024 / 1024 < 2
        if (['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].indexOf(imgType) === -1) {
          this.$message.error('上传图片只能是 JPG、PNG、GIF格式!')
          return false;
        }
        if (!isLtSize) {
          this.$message.error(`上传图片大小不能超过2MB!`)
          return false;
        }
      },
      /** 上传成功后的回调 */
      uploadSuccess(response, file, fileList) {
        console.log("1111");
        console.log(this.fileList);
        console.log(response);
        console.log(file);
        console.log("11112"+ response.fileName);
        this.form.imgPath = response.fileName
        this.files.path = response.fileName
        this.flag = true
      },
      /** 上传成功后的回调 */
      uploadSuccess2(response, file, fileList) {
        console.log("1111");
        console.log(this.fileList);
        console.log(response);
        console.log(file);
        console.log("11112"+ response.fileName);
        this.form.backImgPath = response.fileName
        this.files.path2 = response.fileName
        console.log(this.files.path2);
        this.flag2 = true
      },
    }
  }

</script>
<style scoped>
  .el-upload__tip {
    line-height: 1.2;
  }
  .avatar-uploader i {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader i:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  .form{
    height: 600px;
  }
</style>
